package main

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"github.com/gofiber/fiber"
	"gowork/DepartmentDictionary/utils"
	"log"
	"strconv"
	"time"
)

var x *xorm.Engine

type Department struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	ParentDepartmentId int64
	OrganId string
	DepartmentList []*Department `xorm:"-"`
	AdviserList []*Adviser
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Adviser struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	DepartmentId int64
	GroupId int64
	GroupLeader bool
	DepartmentName string
	CreatedAt time.Time
	UpdatedAt time.Time
}

func QueryDepartment(departmentId int64)(Department, error){

	var d Department
	x.Id(departmentId).Get(&d)

	QuerySubDepartment(&d)

	return d, nil
}

func QuerySubDepartment(d *Department)(){

	x.Where("parent_department_id = ?", d.Id).Find(&d.DepartmentList)
	if len(d.DepartmentList) > 0{
		for _, dv := range d.DepartmentList{
			QuerySubDepartment(dv)
		}
	}
}

func QueryDepartmentByOrganId(organId string)(Department, error){

	var d Department
	x.Where("organ_id = ?", organId).Get(&d)

	QuerySubDepartmentByOrganId(&d)

	return d, nil
}

func QuerySubDepartmentByOrganId(d *Department)(){

	x.SQL("select * from department where organ_id like ? and length(organ_id) = ?", d.OrganId+"%", len(d.OrganId)+2).Find(&d.DepartmentList)
	if len(d.DepartmentList) > 0{
		for _, dv := range d.DepartmentList{
			QuerySubDepartmentByOrganId(dv)
		}
	}else {
		x.Where("department_id = ?", d.Id).Find(&d.AdviserList)
	}
}

func InsertDepartment(departmentList *[]*Department)(map[string]interface{}, error){
	for _, d := range *departmentList{
		x.Insert(d)

		if d.DepartmentList != nil{
			InsertDepartment(&d.DepartmentList)
		}
	}

	return map[string]interface{}{"code":200, "message":"成功"}, nil
}

func main(){

	var xErr error
	x, xErr = xorm.NewEngine("mysql", "root:new_password@tcp(127.0.0.1:3306)/department?charset=utf8")
	if xErr != nil {
		log.Fatal("数据库连接失败:", xErr)
	}
	if err := x.Sync2(new(Department), new(Adviser)); err != nil {
		log.Fatal("数据表同步失败:", err)
	}

	w := new(utils.Worker)
	for i:=1; i<=15; i++ {
		fmt.Println(w.GetId())
	}

	app := fiber.New()

	app.Post("/queryDepartment", func(c *fiber.Ctx){
		departmentIdStr := c.FormValue("departmentId")
		departmentId, err := strconv.ParseInt(departmentIdStr, 10, 64)
		if err != nil {
			c.JSON(fiber.Map{
				"code":    500,
				"data":    nil,
				"message": err.Error(),
			})
			return
		}

		res, err := QueryDepartment(departmentId)
		if err != nil {
			c.JSON(fiber.Map{
				"code":    500,
				"data":    nil,
				"message": err.Error(),
			})
			return
		}

		c.JSON(fiber.Map{
			"code": "200",
			"data": res,
			"message": "成功",
		})
		return
	})

	app.Post("insertDepartment", func(c *fiber.Ctx){

		var departmentList []*Department
		err := c.BodyParser(&departmentList)
		if err != nil {
			c.JSON(fiber.Map{
				"code":    500,
				"data":    nil,
				"message": err.Error(),
			})
			return
		}

		res, err :=InsertDepartment(&departmentList)
		if err != nil {
			c.JSON(fiber.Map{
				"code":    500,
				"data":    nil,
				"message": err.Error(),
			})
			return
		}

		c.JSON(fiber.Map{
			"code": res["code"],
			"data": nil,
			"message": res["message"],
		})
		return
	})

	app.Post("/queryDepartmentByOrganId", func(c *fiber.Ctx){
		organId := c.FormValue("organId")

		res, err := QueryDepartmentByOrganId(organId)
		if err != nil {
			c.JSON(fiber.Map{
				"code":    500,
				"data":    nil,
				"message": err.Error(),
			})
			return
		}

		c.JSON(fiber.Map{
			"code": "200",
			"data": res,
			"message": "成功",
		})
		return
	})

	app.Listen(8263)

}
